local opt = vim.opt
opt.number = true
opt.relativenumber = true
opt.cursorline = true
opt.expandtab = true
opt.tabstop = 2
opt.shiftwidth = 0
opt.autoread = true
opt.termguicolors = true
-- 如果查找的内容中不存在大写，则大小写不敏感
opt.ignorecase = true
opt.smartcase = true
-- 不要在查找之后继续高亮匹配结果
opt.hlsearch = false

--折叠代码块
opt.foldenable = true
opt.foldmethod = "indent"
opt.foldlevel = 99
opt.foldcolumn = "1"

--分屏
opt.splitright = true
opt.splitbelow = true

local keymap = vim.keymap.set
local opts = { noremap = true, silent = true }
vim.g.mapleader = ','
vim.g.maplocalleader = ','
keymap("i", "kj", "<ESC>", opts)
keymap("n", ";", ":", opts)
keymap("n", "<left>", ":bp<CR>", opts)
keymap("n", "<right>", ":bn<CR>", opts)
keymap("i", "<C-l>", "<ESC>A", opts)
-- 核心跳转快捷键
vim.keymap.set('n', 'gd', vim.lsp.buf.definition, opts)
--terminal内进入normal
keymap("t", ",h", "<C-\\><C-n><C-w>h", opts)

--窗口切换
keymap("n", "<C-l>", "<C-w>l", opts)
keymap("n", "<C-h>", "<C-w>h", opts)
keymap("n", "<C-j>", "<C-w>j", opts)
keymap("n", "<C-k>", "<C-w>k", opts)
--标签切换
keymap("n", "<leader>1", "<Cmd>tabn 1<CR>", { desc = "切换到第1个标签页" })
keymap("n", "<leader>2", "<Cmd>tabn 2<CR>", { desc = "切换到第2个标签页" })
keymap("n", "<leader>3", "<Cmd>tabn 3<CR>", { desc = "切换到第2个标签页" })
keymap("n", "<leader>4", "<Cmd>tabn 4<CR>", { desc = "切换到第2个标签页" })

-- 自动居中光标行（在移动光标时）
vim.o.scrolloff = 999 -- 设置较大的值让光标始终保持在中间

--format
keymap("n", "<leader>f",
  function()
    vim.lsp.buf.format()
    vim.api.nvim_command("write")
  end,
  opts
)

local function setup(registry, name, config)
  local success, package = pcall(registry.get_package, name)
  if success and not package:is_installed() then
    package:install()
  end

  local lsp = require("mason-lspconfig").get_mappings().package_to_lspconfig[name]
  vim.lsp.config(lsp, config)
end


-- 确保在 LSP 配置前加载此诊断设置
vim.diagnostic.config({
  -- 显示错误图标（左侧 gutter）
  signs = true,
  -- 错误文字后面显示错误代码（如 [E046]）
  virtual_text = {
    enabled = true,
    prefix = "●", -- 前缀符号
    source = "always" -- 显示错误来源
  },
  -- 光标悬停时显示详细信息
  float = {
    enabled = true,
    source = "always",  -- 显示完整错误信息
    border = "rounded", -- 圆角边框
    header = { "诊断信息:", "DiagnosticHeader" },
    prefix = function(diagnostic)
      local level = vim.diagnostic.severity[diagnostic.severity]
      return "  " .. level .. ": ", "Diagnostic" .. level
    end
  },
  -- 在插入模式下也更新诊断
  update_in_insert = true,
  -- 按严重程度排序显示
  severity_sort = true
})

local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not (vim.uv or vim.loop).fs_stat(lazypath) then
  local lazyrepo = "https://github.com/folke/lazy.nvim.git"
  local out = vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable", lazyrepo, lazypath })
  if vim.v.shell_error ~= 0 then
    vim.api.nvim_echo({
      { "Failed to clone lazy.nvim:\n", "ErrorMsg" },
      { out,                            "WarningMsg" },
      { "\nPress any key to exit..." },
    }, true, {})
    vim.fn.getchar()
    os.exit(1)
  end
end
vim.opt.rtp:prepend(lazypath)

require("lazy").setup({
  {
    "folke/tokyonight.nvim",
    lazy = false,    -- make sure we load this during startup if it is your main colorscheme
    priority = 1000, -- make sure to load this before all the other start plugins
    config = function()
      -- load the colorscheme here
      vim.cmd([[colorscheme tokyonight]])
    end,
  },
  {
    'akinsho/bufferline.nvim',
    version = "*",
    dependencies = 'nvim-tree/nvim-web-devicons',
    lazy = false,
    opts = {
      options = {
        mode = "tabs",
        diagnostics = "nvim_lsp",
        diagnostics_indicator = function(_, _, diagnostics_dict, _)
          local indicator = " "
          for level, number in pairs(diagnostics_dict) do
            local symbol
            if level == "error" then
              symbol = " "
            elseif level == "warning" then
              symbol = " "
            else
              symbol = " "
            end
            indicator = indicator .. number .. symbol
          end
          return indicator
        end
      }
    }

  },
  -- 自动括号等,
  {
    'windwp/nvim-autopairs',
    event = "InsertEnter",
    config = true,
    -- use opts = {} for passing setup options
    -- this is equivalent to setup({}) function
  },
  --自动环绕括号等
  {
    "kylechui/nvim-surround",
    version = "^3.0.0", -- Use for stability; omit to use `main` branch for the latest features
    event = "VeryLazy",
    config = function()
      require("nvim-surround").setup({
        -- Configuration here, or leave empty to use defaults
      })
    end
  },

  --lsp管理器
  {
    "mason-org/mason.nvim",
    event = "VeryLazy",
    dependencies = {
      "neovim/nvim-lspconfig",
      "mason-org/mason-lspconfig.nvim",
    },
    opts = {},
    config = function(_, op)
      require("mason").setup(op)
      local registry = require "mason-registry"
      setup(registry, "lua-language-server", {
        settings = {
          Lua = {
            diagnostics = {
              globals = { "vim" },
            },
            workspace = {
              ignoreDir = { "xmake.lua" }
            }
          }
        }
      })
      setup(registry, "clangd", {
        cmd = {
          "clangd",
          "--fallback-style=Google", -- 可选: LLVM, Google, Chromium, Mozilla, WebKit
          "--header-insertion=never",
        },
      })
      vim.cmd("LspStart")
    end,
  },
  --补全
  {
    "saghen/blink.cmp",
    version = "*",
    dependencies = {
      "rafamadriz/friendly-snippets",
    },
    event = "VeryLazy",
    opts = {
      completion = {
        documentation = {
          auto_show = true,
        },
      },
      keymap = {
        preset = "super-tab",
      },
      sources = {
        default = { "path", "snippets", "buffer", "lsp" },
      },
      cmdline = {
        sources = function()
          local cmd_type = vim.fn.getcmdtype()
          if cmd_type == "/" or cmd_type == "?" then
            return { "buffer" }
          end
          if cmd_type == ":" then
            return { "cmdline" }
          end
          return {}
        end,
        keymap = {
          preset = "super-tab",
        },
        completion = {
          menu = {
            auto_show = true,
          },
        },
      },
    },

  },
  --目录
  {
    "nvim-tree/nvim-tree.lua",
    dependencies = { "nvim-tree/nvim-web-devicons" },
    opts = {
      actions = {
        open_file = {
          quit_on_open = true,
        },
      },
    },
    keys = {
      { "<leader>n", ":NvimTreeToggle<CR>" },
    },
  },
  --dot repeat 增强
  { "tpope/vim-repeat", event = "VeryLazy" },
  --文件内快速定位
  {
    "ggandor/leap.nvim",
    config = function()
      local leap = require('leap')
      leap.add_default_mappings()
      leap.opts.case_sensitive = true
    end
  },
  {
    "rmagatti/auto-session",
    lazy = false,

    ---enables autocomplete for opts
    ---@module "auto-session"
    ---@type AutoSession.Config
    opts = {
      suppressed_dirs = {},
      -- log_level = 'debug',
    },
  }
  --xmake
  -- {
  --     "Mythos-404/xmake.nvim",
  --     version = "^3",
  --     lazy = true,
  --     event = "BufReadPost",
  --     config = true,
  -- }

})
